<?php

use Illuminate\Database\Seeder;

class AreaBuildSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        if (\App\B2BProject\Area::count() > 5000) {
            return;
        }

        if (file_exists(__DIR__ . '/map.json')) {
            $json = file_get_contents(__DIR__ . '/map.json');

            $map = json_decode($json, true);

            foreach ($map as $l1) {
                $province = \App\B2BProject\Area::create(['name' => $l1['name'], 'level' => 1]);

                if (isset($l1['children'])) {
                    foreach ($l1['children'] as $l2) {
                        $city = \App\B2BProject\Area::create(['name' => $l2['name'], 'level' => 2]);

                        if (isset($l2['children'])) {
                            foreach ($l2['children'] as $l3) {
                                $city->children()->save(\App\B2BProject\Area::create(['name'  => $l3['name'],
                                                                                      'level' => 3,
                                ]));
                            }
                        }

                        $province->children()->save($city);
                    }
                }
            }
        }
    }
}
